import { login, logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'

const getDefaultState = () => {
  return {
    token: getToken(),
    userInfo:{ //用户信息
      name:"",
      avatar:"",
      roles:[],
      buttons:[],
      routes:[]
    },
    
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_USERINFO(state,userInfo){
    state.userInfo = userInfo
  }
}

const actions = {
  // user login 登录请求
  async login({ commit }, userInfo) {
    const { username, password } = userInfo
    try {
      const result = await login({ username: username.trim(), password: password })
      commit('SET_TOKEN', result.token)
      setToken(result.token)
    } catch (error) {
      this.$message({
        message: error.message,
        type: 'error'
      })
    }
  },

  // get user info
  async getInfo({ commit, state }) {
    try {
      const result = await getInfo()
      commit("SET_USERINFO",result)
    } catch (error) {
      this.$message({
        message: error.message,
        type: 'error'
      })
    }
  },

  // user logout
  async logout({ commit, state }) {
    try {
      await logout()
      removeToken()
      resetRouter()
      commit('RESET_STATE')
    } catch (error) {
      this.$message({
        message: error.message,
        type: 'error'
      })
    }
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

